const api = require("./config/api")
const request = require("./utils/request")
import tim from "./utils/tim/tim"
import { getSceneCode, getScreenSize, getStorage, setStorage, removeStorage, jump, getTodayDate, getCurrentPage } from "./utils/utils"
import { getUserLocation , logout } from "./utils/access";
const miniShopPlugin = requirePlugin('mini-shop-plugin');

// app.js
App({
  onLaunch(options) {
    // 存储小程序来源
    setStorage('smallRoutine', options?.referrerInfo?.extraData?.source || '')
    console.log('屏幕尺寸：', getScreenSize())
    // 加载商店交易组件
    miniShopPlugin.initApp(this, wx);
  },
 onShow(options) {
    console.log('options',options)
    this.recordStartTime = Date.now()
    this.globalData.systemInfo = wx.getSystemInfoSync()
    this.globalData.miniProgramInfo = wx.getAccountInfoSync()?.miniProgram
    console.log('小程序打开', this.globalData);
    this.globalData.options = options
    // 小程序更新
    // this.update()
    // 打开上报
    this.openReport()
  
    // tim初始化
    tim.init()
    // 获取tim用户签名
    if (this.isLogin()) {
      tim.getUserSig()
    } 

    removeStorage('fromShare')
    removeStorage('shareSource')
    if (options.path === 'pages/index/index') {
      console.log('小程序唤起', options);
      // this.jumpSpecialHome()
    }
    if(options.path === 'pages/idleHome/idleHome'){
      this.jumpIdleHome()
    }
    if(options.path === 'pages/openScreen/openScreen'){
      if(Number(options.query.share)===1){
        // 设置缓存，25天拍照 若是分享链接打开，操作时需要加限制
        setStorage('fromShare','25DayTask')
      }
      if(Number(options.query.share)===2){
        // 设置缓存，分享领鸡蛋 若是分享链接打开，操作时需要加限制
        setStorage('fromShare','shareFromWechat')
        // 设置缓存 分享来源 1：拍照任务分享奖励
        setStorage('shareSource', 1)
        setStorage('activityId', options?.query?.activityId)
      }

      if (options?.query?.shareUserId) {
        setStorage('shareUserId', options?.query?.shareUserId)
      }

      this.jumpActivity()
    }
    if(options.path === 'pages/userAward/userAward'){
      this.jumpReward()
    }
  },
  onHide() {
    this.globalData.recordStayTime = Date.now() - (this.recordStartTime || Date.now())
    this.globalData.path = getCurrentPage()
    if (!this.globalData.userId && getStorage('userId')) {
      this.globalData.userId = getStorage('userId')
    }
    if (!this.globalData.swapData && getStorage('openId')) {
      this.globalData.swapData = {
        openid: getStorage('openId')
      }
    }
    // 关闭上报
    this.closeReport()
    console.log('小程序隐藏');
    removeStorage('fromShare')
  },
  // 小程序更新
  update() {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log('小程序新版本信息：', res)
    })

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        showCancel: false,
        success: function (res) {
          console.log('小程序更新：', res)
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    updateManager.onUpdateFailed(function (err) {
      // 新版本下载失败
      console.log('小程序更新失败：', err)
    })
  },
  // 获取openId
  async getOpenId() {
    if (!getStorage('swapData')?.openid && !getStorage('openId')) {
      await this.getSwapData(true)
    }
    const options = this.globalData.options
    if (options?.path==="pages/voteActiveDetail/voteActiveDetail" && options.query.scene) {
      var scene = decodeURIComponent(options.query.scene);
      console.log("scene is ", scene);
      if (scene) {
        let arr = scene.split("=");
                console.log("scene:", arr[0], "=", arr[1]);
                // 分享卡片进来  保存卡片点击记录
               if(arr[0] === 'inviteId'){
                  let openId = getStorage('openId')
                  let res = await request.get(api.voteCardClick,{
                      openId,
                      communityId: arr[1]
                  },{ loading:false })
                  console.log('卡片点击记录---',res)
               }
            }
    }
  },
  // 打开上报
  async openReport() {
    await this.getOpenId()
    const { systemInfo, miniProgramInfo } = this.globalData || {}
    const { version, SDKVersion, brand, model, system, platform } = systemInfo || {}
    const res = await request.post(api.activityUserReportNew, {
      viewId: getStorage('swapData')?.openid || getStorage('openId'), // 小程序openid或用户id
      open: 1, // 1 小程序打开 2 小程序关闭
      url: getCurrentPage(),
      wechatVersion: version, // 微信版本
      version: miniProgramInfo?.version, // 小程序版本号
      sdkVersion: SDKVersion, // 小程序SDK版本号
      brand, // 手机品牌
      model, // 手机型号
      system, // 操作系统及版本
    }, { modal: false, loading: false })
    this.ticket = res?.httpStatus === 200 ? res?.data : null
    console.log('小程序打开上报：', res);
  },
  // 关闭上报
  async closeReport() {
    await this.getOpenId()
    const { systemInfo, miniProgramInfo } = this.globalData || {}
    const { version, SDKVersion, brand, model, system, platform } = systemInfo || {}
    const res = await request.post(api.activityUserReportNew, {
      field: this.ticket,
      // userId: getStorage('userId'), // 用户id
      viewId: getStorage('swapData')?.openid || getStorage('openId'), // 小程序openid或用户id
      url: getCurrentPage(),
      open: 2, // 1 小程序打开 2 小程序关闭
      wechatVersion: version, // 微信版本
      version: miniProgramInfo?.version, // 小程序版本号
      sdkVersion: SDKVersion, // 小程序SDK版本号
      brand, // 手机品牌
      model, // 手机型号
      system, // 操作系统及版本
      // platform, // 客户端平台
    }, { modal: false, loading: false })
    console.log('小程序关闭上报：', res);
  },
  // 先关闭上报后打开上报
  async switchReport() {
    await this.closeReport()
    await this.openReport()
  },
  // 检查用户活跃状态
  async checkActivityStatus() {
    const res = await request.get(api.isActivityUser, null, { modal: false, loading: false })
    console.log('是否已经完成活跃：', res?.data);
    const stayInfo = getStorage('stayInfo') || {}
    const { year, month, day } = getTodayDate()
    const todayDate = `${year}${month}${day}`
    stayInfo.date = todayDate
    if (res?.data) {
      if (stayInfo.duration < this.stayTimeMax) {
        stayInfo.duration = this.stayTimeMax + 1
      }
      stayInfo.done = 1
    } else {
      stayInfo.done = 0
    }
    setStorage('stayInfo', stayInfo)
  },
  // 判断是否已经登录并且是目标用户，跳转开屏页
  async jumpSpecialHome() {
    if (this.isLogin()) {
      const res = await request.get(api.userType, null, { loading: false })

      // 用户类型 1普通用户 2目标用户
      setStorage("userType", res?.data ? 2 : 1)
      console.log("目标用户：", res?.data)

      if (res?.data) {
        jump('openScreen')
      }
    }
  },
  // 闲置页分享后打开页面
  jumpIdleHome(){
    // 用户未登录、未授权地理位置,跳转便民页面
    if (!this.isLogin()) {
      jump('convenience')
    }
    // 未授权地理位置
    if (!getUserLocation()) {
      jump('convenience')
    } 
  },
  // 25天活动、抽奖活动
  jumpActivity(){
    
    // 用户未登录
    if (!this.isLogin()) {
      setStorage('redirectPath', '/pages/openScreen/openScreen')
      logout()
      return
    }
  },
  // 用户奖励页面
  jumpReward(){
    // 用户未登录
    if (!this.isLogin()) {
      setStorage('redirectPath', '/pages/userAward/userAward')
    }
  },
  /**
   * 信息弹窗
   * @param {*} msg 信息
   */
  message(msg = "登录失败") {
    wx.showModal({
      content: msg,
    })
  },

  /**
   * 获取openId, sessionKey, unionId
   */
  async getSwapData(onlyOpenId) {
    return new Promise((resolve) => {
      wx.login({
        success: async (response) => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (response?.code) {
            const res = await request.get(api.authSwap, {
              code: response.code,
            }, { loading: !onlyOpenId })
            if (res?.httpStatus == 200) {
              const swapData = res?.data || {}
              if (onlyOpenId) {
                setStorage('openId', swapData?.openid)
              } else {
                this.globalData.swapData = swapData
                setStorage("swapData", swapData)
              }
              resolve(swapData)
            } else {
              this.message(res?.msg)
              resolve(null)
            }
          } else {
            this.message()
            resolve(null)
          }
        },
        error: () => {
          this.message()
          resolve(null)
        },
      })
    })
  },

  /**
   * 登录绑定用户信息
   */
  async login() {
    if (this.globalData.logining) return
    this.globalData.logining = true
    // 用户信息
    this.clearLogin()
    const profile = await new Promise((resolve) => {
      wx.getUserProfile({
        desc: "用于用户登录",
        success: (res) => {
          resolve(res)
        },
        error: () => {
          this.message("授权失败")
          resolve(null)
        },
        complete: () => {
          this.globalData.logining = false
        },
      })
    })
    console.log(profile, "第一次获取用户的数据")
    this.globalData.userInfo = profile?.userInfo
    setStorage("userInfo", profile?.userInfo)
    // 获取openId, sessionKey, unionId
    await this.getSwapData()
    if (getStorage('redirectPath')) {
      wx.redirectTo({
        url: "/pages/login/login",
      })
    } else {
      wx.navigateTo({
        url: "/pages/login/login",
      })
    }
    return profile?.userInfo
  },

  /**
   * 微信登录
   */
  async wxLogin(profile) {
    const userInfo = this.globalData.userInfo || getStorage("userInfo")
    const swapData = this.globalData.swapData
    const { encryptedData, iv } = profile
    console.log('userInfo---',userInfo)
    if (!swapData?.sessionKey) {
      await this.getSwapData()
      this.message("登录失败！")
      return false
    }
    if (!encryptedData || !iv || !userInfo){
      this.message("登录失败！")
      return false
    }
    // 获取手机号&token
    const params = {
        encryptedData,
        ivStr: iv,
        icon: userInfo?.avatarUrl,
        gender: userInfo?.gender,
        nickName: userInfo?.nickName,
        sessionKey: swapData?.sessionKey,
        unionId: swapData?.unionId,
        openId: swapData?.openid,
        // 场景ID
        scene: getSceneCode()
    }
    if(getStorage("shareSource")){ // 分享
      params['content'] = getStorage("shareUserId")
      params['type'] = 1
      params['activityId'] = getStorage("activityId")
    } else if(getStorage("invite_user_id") || getStorage("inviteData")){ // 邀请
       params['content'] = getStorage("invite_user_id") || getStorage("inviteData")
       params['type'] = 1
    }else if(getStorage("new_invite_user_id")){ // 新邀请
       params['content'] = getStorage("new_invite_user_id")
       params['type'] = 1
       params['activityId'] = 18
    }else if(getStorage("platform")){ // 平台
       params['content'] = getStorage("platform")
       params['type'] = 2
    }else if(getStorage("smallRoutine")){ // 小程序来源
       params['content'] = getStorage("smallRoutine")
       params['type'] = 3
    }
    console.log('params---',params)
    const res = await request.post(api.authBind, params)
    console.log(res, "--------------------")
    console.log(res.data.userId)
    // 取出先前的userInfo
    const newUserInfo = getStorage("userInfo")
    // 改变其中的nickName值
    newUserInfo.nickName = res?.data?.nickName
    // 储存到缓存中
    if (res?.httpStatus === 200) {
      this.globalData.userId = res?.data?.userId
      console.log("token", res.data.token)
      setStorage("userInfo", newUserInfo || " ")
      setStorage("userIdentity", res.data?.userIdentity || " ")
      setStorage("phone", res.data?.phone || " ")
      setStorage("token", res.data?.token || " ")
      setStorage("userId", res.data?.userId || " ")
      // 用户类型 1普通用户 2目标用户
      setStorage("userType", res.data?.target ? 2 : 1)

      // const checkRes = await request.get(api.checkIsFail, {})

      // if (checkRes.httpStatus == 200) {
      //   // 无任务直接开启挑战
      //   if (checkRes.data?.status == 4) {
      //     request.get(api.startChallenge, {})
      //   }
      // }

      // 邀请：判断是否需要完善资料
      if(params.type && params.type === 1){
        const { data } = await request.get(api.needSupply,{'userId': getStorage("invite_user_id") || getStorage("inviteData")})
        // setStorage("supply", data)
      }else{
        setStorage("supply", false)
      }
      // 先关闭上报后打开上报
      this.switchReport()
      // 获取tim用户签名
      tim.getUserSig()
      return true
    } else {
      this.message(res?.msg || "登录失败！")
    }
    return false
  },

  /**
   * 清除登录状态
   */
  clearLogin() {
    removeStorage("token")
    removeStorage("phone")
    removeStorage("swapData")
    removeStorage("userInfo")
    removeStorage("latitude")
    removeStorage("longitude")
    removeStorage("addressInfo")
    removeStorage("communityBind")
    removeStorage("communityName")
    removeStorage("communityCode")
    removeStorage("userIdentity")
    removeStorage("newMsgNum")
    removeStorage("newCouponNum")
    this.globalData.swapData = null
    this.globalData.userInfo = null
  },

  /**
   * 是否已经登录
   */
  isLogin() {
    const token = getStorage("token")
    return !!token
  },

  /**
   * 获取用户信息
   */
  userInfo() {
    return getStorage("userInfo")
  },

  /**
   * 获取用户id
   */
  userId() {
    return getStorage("userId")
  },

  // 检查是否是目标小区
  checkIsTarget(callback) {
    if (!this.isLogin()) {
      callback?.(false)
      this.globalData.isTargetCommunity = false
      return
    }
    request.get(api.getAuthStatus, {}, { loading: false, modal: false })
      .then((res) => {
        const isTargetCommunity = Boolean(res?.data?.ifTargetCommunity)
        this.globalData.isTargetCommunity = isTargetCommunity
        callback?.(isTargetCommunity)
      })
      .catch(() => {
        this.globalData.isTargetCommunity = false
        callback?.(false)
      })
  },
  // 监听事件列表
  events: {},
  // 新增事件监听
  on(name, callback, self) {
    const tuple = [self, callback]
    const callbacks = this.events[name]
    if (Array.isArray(callbacks)) {
      callbacks.push(tuple)
    } else {
      this.events[name] = [tuple]
    }
  },
  // 移除事件监听
  off(name, self) {
    const callbacks = this.events[name]
    if (Array.isArray(callbacks)) {
      this.events[name] = callbacks.filter((tuple) => tuple[0]?.route !== self?.route)
      console.log(callbacks, this.events[name], 22222);
    }
  },
  // 触发事件
  emit(name, data) {
    const callbacks = this.events[name]
    if (Array.isArray(callbacks)) {
      callbacks.map(([self, callback]) => {
        callback?.call(self, data)
      })
    }
  },
  globalData: {
    // openId, sessionKey, unionId
    swapData: null,
    // 用户信息
    userInfo: null,
    // 登录状态
    logining: false,
    // 是否是目标小区
    isTargetCommunity: false,
  },
})
